package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxBlCost;
import com.adk.backend.entity.LxBlList;
import com.adk.backend.service.BlService;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/bl")
public class BlController {
    
    @Autowired
    private BlService blService;
    
    @Autowired
    private LogUtil logUtil;
    
    /**
     * 分页查询提单列表
     */
    @RequiresPermission("list")
    @GetMapping("/list")
    public Result<PageResult<Map<String, Object>>> getBlList(
            @RequestParam(required = false) String blNo,
            @RequestParam(required = false) String blDate,
            @RequestParam(required = false) String obDate,
            @RequestParam(required = false) Integer vndTxId,
            @RequestParam(required = false) Integer tx,
            @RequestParam(required = false) Integer vndZgId,
            @RequestParam(required = false) Integer zg,
            @RequestParam(required = false) Integer mf,
            @RequestParam(required = false) Integer hll,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) String opUser,
            @RequestParam(required = false) String op,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("blNo", blNo);
        // 优先使用 obDate，如果没有则使用 blDate
        if (obDate != null && !obDate.isEmpty()) {
            params.put("blDate", obDate);
        } else {
            params.put("blDate", blDate);
        }
        // 优先使用 tx，如果没有则使用 vndTxId
        if (tx != null && tx > 0) {
            params.put("vndTxId", tx);
        } else {
            params.put("vndTxId", vndTxId);
        }
        // 优先使用 zg，如果没有则使用 vndZgId
        if (zg != null && zg > 0) {
            params.put("vndZgId", zg);
        } else {
            params.put("vndZgId", vndZgId);
        }
        params.put("mf", mf);
        params.put("hll", hll);
        params.put("shipType", shipType);
        // 优先使用 op，如果没有则使用 opUser
        if (op != null && !op.isEmpty()) {
            params.put("opUser", op);
        } else {
            params.put("opUser", opUser);
        }
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        PageResult<Map<String, Object>> result = blService.getBlList(params);
        return Result.success(result);
    }
    
    /**
     * 根据ID查询提单详情
     */
    @RequiresPermission("view")
    @GetMapping("/detail")
    public Result<LxBlList> getBlDetail(@RequestParam Integer id) {
        LxBlList bl = blService.getBlById(id);
        if (bl != null) {
            return Result.success(bl);
        }
        return Result.error("提单不存在");
    }
    
    /**
     * 根据提单号查询提单
     */
    @RequiresPermission("view")
    @GetMapping("/by-blno")
    public Result<LxBlList> getBlByBlNo(@RequestParam String blNo) {
        LxBlList bl = blService.getBlByBlNo(blNo);
        if (bl != null) {
            return Result.success(bl);
        }
        return Result.error("提单不存在");
    }
    
    /**
     * 创建提单
     */
    @RequiresPermission("add")
    @PostMapping("/create")
    public Result<LxBlList> createBl(@RequestBody LxBlList blList, HttpServletRequest httpRequest) {
        try {
            // 检查提单号是否已存在
            LxBlList existing = blService.getBlByBlNo(blList.getBlNo());
            if (existing != null) {
                return Result.error("提单号已存在");
            }
            
            Long userId = (Long) httpRequest.getAttribute("userId");
            LxBlList result = blService.createBl(blList, userId != null ? userId.intValue() : null);
            return Result.success("操作成功", result);
        } catch (Exception e) {
            log.error("创建提单失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 更新提单
     */
    @RequiresPermission("edit")
    @PostMapping("/update")
    public Result<Boolean> updateBl(@RequestBody LxBlList blList, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.updateBl(blList, userId != null ? userId.intValue() : null);
            if (success) {
                return Result.success("修改成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("更新提单失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 删除提单
     */
    @RequiresPermission("del")
    @PostMapping("/delete")
    public Result<Boolean> deleteBl(@RequestParam Integer id) {
        try {
            boolean success = blService.deleteBl(id);
            if (success) {
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除提单失败", e);
            return Result.error("删除提单失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取提单成本列表
     */
    @RequiresPermission("view")
    @GetMapping("/cost/list")
    public Result<java.util.List<LxBlCost>> getBlCosts(@RequestParam Integer blId) {
        java.util.List<LxBlCost> costs = blService.getBlCosts(blId);
        return Result.success(costs);
    }
    
    /**
     * 添加提单成本
     */
    @RequiresPermission("cost_add")
    @PostMapping("/cost/add")
    public Result<Boolean> addBlCost(@RequestBody LxBlCost blCost) {
        try {
            boolean success = blService.addBlCost(blCost);
            if (success) {
                return Result.success("添加成功", true);
            }
            return Result.error("添加失败");
        } catch (Exception e) {
            log.error("添加提单成本失败", e);
            return Result.error("添加提单成本失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存提单成本（批量保存）
     */
    @RequiresPermission("cost_save")
    @PostMapping("/cost/save")
    public Result<Boolean> saveBlCosts(@RequestParam Integer id, 
                                        @RequestBody List<LxBlCost> blCosts,
                                        HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.saveBlCosts(id, blCosts, userId != null ? userId.intValue() : null);
            if (success) {
                return Result.success("操作成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("保存提单成本失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 更新提单成本
     */
    @RequiresPermission("cost_save")
    @PostMapping("/cost/update")
    public Result<Boolean> updateBlCost(@RequestBody LxBlCost blCost, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.updateBlCost(blCost, userId != null ? userId.intValue() : null);
            if (success) {
                return Result.success("操作成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("更新提单成本失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 删除提单成本
     */
    @RequiresPermission("cost_del")
    @PostMapping("/cost/delete")
    public Result<Boolean> deleteBlCost(@RequestParam Long id) {
        try {
            boolean success = blService.deleteBlCost(id);
            if (success) {
                return Result.success("删除成功", true);
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除提单成本失败", e);
            return Result.error("删除提单成本失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取提单明细列表
     */
    @RequiresPermission("view")
    @GetMapping("/details/list")
    public Result<java.util.List<Map<String, Object>>> getBlDetailsList(@RequestParam Integer blId) {
        java.util.List<Map<String, Object>> details = blService.getBlDetailsWithOrder(blId);
        return Result.success(details);
    }
    
    /**
     * 获取HLL费用信息
     */
    @RequiresPermission("view")
    @GetMapping("/hll-fee")
    public Result<Map<String, Object>> getHllFee(@RequestParam Integer id) {
        Map<String, Object> result = blService.getHllFee(id);
        return Result.success(result);
    }
    
    /**
     * 保存HLL费用
     */
    @RequiresPermission("edit")
    @PostMapping("/hll-fee/save")
    public Result<Boolean> saveHllFee(@RequestParam Integer id, @RequestParam java.math.BigDecimal hllFee, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.saveHllFee(id, hllFee, userId != null ? userId.intValue() : null);
            if (success) {
                // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "order_list", $id, "设置货拉拉费用");）
                // 注意：PHP代码中$id是提单ID，但日志记录到order_list表。这里需要获取关联的订单ID
                if (userId != null) {
                    List<Map<String, Object>> blDetails = blService.getBlDetailsWithOrder(id);
                    if (blDetails != null && !blDetails.isEmpty()) {
                        // 获取第一个订单ID记录日志（与PHP逻辑一致）
                        Long orderId = Long.valueOf(blDetails.get(0).get("o_id").toString());
                        logUtil.logAction(userId, "order_list", orderId, "设置货拉拉费用");
                    }
                }
                return Result.success("修改成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("保存HLL费用失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 获取Manifest费用信息
     */
    @RequiresPermission("view")
    @GetMapping("/manifest-fee")
    public Result<Map<String, Object>> getManifestFee(@RequestParam Integer id) {
        Map<String, Object> result = blService.getManifestFee(id);
        return Result.success(result);
    }
    
    /**
     * 保存Manifest费用
     */
    @RequiresPermission("edit")
    @PostMapping("/manifest-fee/save")
    public Result<Boolean> saveManifestFee(@RequestParam Integer id, @RequestParam java.math.BigDecimal mainfestFee, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.saveManifestFee(id, mainfestFee, userId != null ? userId.intValue() : null);
            if (success) {
                // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "order_list", $id, "设置Manifest申报金额");）
                if (userId != null) {
                    List<Map<String, Object>> blDetails = blService.getBlDetailsWithOrder(id);
                    if (blDetails != null && !blDetails.isEmpty()) {
                        Long orderId = Long.valueOf(blDetails.get(0).get("o_id").toString());
                        logUtil.logAction(userId, "order_list", orderId, "设置Manifest申报金额");
                    }
                }
                return Result.success("修改成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("保存Manifest费用失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 获取中港信息
     */
    @RequiresPermission("view")
    @GetMapping("/zg-info")
    public Result<Map<String, Object>> getZgInfo(@RequestParam Integer id) {
        Map<String, Object> result = blService.getZgInfo(id);
        return Result.success(result);
    }
    
    /**
     * 保存中港信息
     */
    @RequiresPermission("edit")
    @PostMapping("/zg-info/save")
    public Result<Boolean> saveZgInfo(@RequestParam Integer id, 
                                       @RequestParam(required = false) String zgBlNo,
                                       @RequestParam(required = false) Integer vndZgId,
                                       HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.saveZgInfo(id, zgBlNo, vndZgId, userId != null ? userId.intValue() : null);
            if (success) {
                // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "order_list", $id, "设置中港信息");）
                if (userId != null) {
                    List<Map<String, Object>> blDetails = blService.getBlDetailsWithOrder(id);
                    if (blDetails != null && !blDetails.isEmpty()) {
                        Long orderId = Long.valueOf(blDetails.get(0).get("o_id").toString());
                        logUtil.logAction(userId, "order_list", orderId, "设置中港信息");
                    }
                }
                return Result.success("修改成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("保存中港信息失败", e);
            return Result.error("数据错误");
        }
    }
    
    /**
     * 获取头程公司信息
     */
    @RequiresPermission("view")
    @GetMapping("/tx-info")
    public Result<Map<String, Object>> getTxInfo(@RequestParam Integer id) {
        Map<String, Object> result = blService.getTxInfo(id);
        return Result.success(result);
    }
    
    /**
     * 保存头程公司信息
     */
    @RequiresPermission("edit")
    @PostMapping("/tx-info/save")
    public Result<Boolean> saveTxInfo(@RequestParam Integer id, @RequestParam Integer vndTxId, HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean success = blService.saveTxInfo(id, vndTxId, userId != null ? userId.intValue() : null);
            if (success) {
                // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "order_list", $id, "设置头程公司");）
                if (userId != null) {
                    List<Map<String, Object>> blDetails = blService.getBlDetailsWithOrder(id);
                    if (blDetails != null && !blDetails.isEmpty()) {
                        Long orderId = Long.valueOf(blDetails.get(0).get("o_id").toString());
                        logUtil.logAction(userId, "order_list", orderId, "设置头程公司");
                    }
                }
                return Result.success("修改成功", true);
            }
            return Result.error("数据错误");
        } catch (Exception e) {
            log.error("保存头程公司信息失败", e);
            return Result.error("数据错误");
        }
    }
}

